package com.handpay.zztong.hp.main.widget.icon;

import android.content.Intent;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.swiper.SwiperMode;
import com.handpay.zztong.hp.R;

import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.db.ormlite.DataBaseComponentModel;
import com.handpay.zztong.hp.main.model.component.ComponentRelationItemBean;
import com.handpay.zztong.hp.main.widget.dialog.blur.BlurDialogFragment;
import com.handpay.zztong.hp.onlineshop.activity.JieAnHtmlActivity;
import com.handpay.zztong.hp.onlineshop.activity.ShowLoanHtmlActivity;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.onlineshop.activity.ShowMarketHtmlActivity;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.activity.AllFunctionActivity;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.main.model.FunctionInfo;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.webpay.activity.ScannerCodePayActivity;
import com.handpay.zztong.hp.withdraw.activity.WithdrawActivity;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.sobot.chat.utils.LogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by lyang on 2017/1/10.
 */

public class IconBaseOnItemClickListener implements AdapterView.OnItemClickListener {
    private ZZTongActivity mActivity;
    private BlurDialogFragment dialogFragment;
    private DataBaseComponentModel mDBModel;
    private long mLastClickTime = 0;

    public IconBaseOnItemClickListener(ZZTongActivity activity) {
        mActivity = activity;
        mDBModel = new DataBaseComponentModel(mActivity);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        // 避免多次点击
        if (SystemClock.elapsedRealtime() - mLastClickTime < ZZTConstant.NO_RESPONSE_CLICK_TIME) {
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();
        String tag = ((IconBaseAdapter) adapterView.getAdapter()).getData().get(position);
        gridViewItemOnclick(tag);
    }

    public void gridViewItemOnclick(String tag) {
        HashMap<String, FunctionInfo> maps = FunctionInfo.getFunctionInfos(mActivity.getApplicationContext());
        FunctionInfo info = maps.get(tag);
        if (info.type.equals("2")) {
            List<ComponentRelationItemBean> list = mDBModel.queryComponentRelationByParentItemCode(info.itemId);
            ArrayList mData = new ArrayList<String>();
            for (ComponentRelationItemBean bean : list) {
                mData.add(bean.getItemCode());
            }
            if (dialogFragment == null) {
                dialogFragment = new BlurDialogFragment();
            }
            if (dialogFragment.getDialog() == null || dialogFragment.getDialog().isShowing() == false) {
                dialogFragment.setIconData(mData);
                dialogFragment.fadeIn(mActivity, "dialog");
            }
            return;
        }

        if (info.itemId.equalsIgnoreCase(FunctionInfo.COLLECT_MONEY_CODE)) {
            switchPage();
        } else if (tag.equalsIgnoreCase(FunctionInfo.FAST_TRANSFER_CODE) || tag.equalsIgnoreCase(FunctionInfo.CREDIT_CARD_CODE)) {
            startTransferActivity(info, true);
        } else if (tag.equalsIgnoreCase(FunctionInfo.NO_CARD_PAYMENT_CODE)) {
            String host;
            host = mDBModel.queryComponent(info.itemId).getItemUrl();
            if (TextUtils.isEmpty(host)) {
                host = "https://wallet.handpay.cn/hpayJHSupport/scan2/wap/entrance.htm";
            }
            String url;
            String merchantCode = AccountUtils.getMerchantCode(mActivity);
            url = host + "?merchantCode=" + merchantCode + "&channel=" + ClientEngine.CHANNEL;
            startShowHtmlActivity("无卡支付", url);
        } else if (tag.equalsIgnoreCase(FunctionInfo.MOBILE_RECHARGE_CODE)) {
            startShowHtmlActivity(mActivity.getString(R.string.phone_charge), ZZTConfig.PHONE);
                    /*startActivity(new Intent(mActivity, RechargeMainActivity.class));*/
        } else if (tag.equalsIgnoreCase(FunctionInfo.HONG_SHOP_CODE)) {
            if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {
                Toast.makeText(mActivity, mActivity.getString(R.string.QualificationsPromptVOP_4), Toast.LENGTH_SHORT).show();
            } else {
                String host;
                host = mDBModel.queryComponent(info.itemId).getItemUrl();
                if (TextUtils.isEmpty(host)) {
                    host = "http://ds.handmart.cn/NewApp/Hylogin.aspx";
                }
                startShowPaymentHtmlActivity(mActivity.getString(R.string.distribution_system), host + "?merchantCode=" + AccountUtils.getMerchantCode(mActivity));
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.MY_COLLECT_LIMIT_CODE)) {
            if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {
                mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), mActivity.getString(R.string.toast_need_tip));
                return;
            }

            if (mActivity.getClass() == MainActivity.class) {
                ((MainActivity) mActivity).getCurrentFragment().doShouKuanXianE();
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.MY_COLLECT_WITHDRAW_CODE)) {
            doWithDrawCash();
        } else if (tag.equalsIgnoreCase(FunctionInfo.MY_QUALIFICATION_INFO_CODE)) {
            if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {
                if (mActivity.getClass() == MainActivity.class) {
                    ((MainActivity) mActivity).getCurrentFragment().doZiZhiTiJiao();
                }
            } else {
                Intent intent = new Intent(mActivity, info.cls);
                mActivity.startActivity(intent);
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.MY_SWIPE_SELECT_CODE)) {
            Intent intent = new Intent(mActivity, info.cls);
            swiperConnect(intent);
        } else if (tag.equalsIgnoreCase(FunctionInfo.MY_T0_QUALIFICATION_CODE) && !AccountUtils.getAccountStatus(mActivity).equals(AccountUtils.AccountStatus.SUCCESS)) {
            showNeedUpload();
        } else if (tag.equalsIgnoreCase(FunctionInfo.MY_COLLECT_CARD_MANAGEMENT_CODE)) {
            if (!AccountUtils.getAccountStatus(mActivity).equals(AccountUtils.AccountStatus.SUCCESS)) {
                showNeedUpload();
            } else {
                Intent intent = new Intent(mActivity, info.cls);
                mActivity.startActivity(intent);
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.QQ_IM_CODE)) {
            openSoBotApplication();
        } else if (tag.equalsIgnoreCase(FunctionInfo.STOCK_FUND_CODE)) {
            String url = "https://aop.ect888.com/pm/open/index.html?channel_key=LMujPYwYBio0wLqY&channel_no=YKH0061&channel_userid=" + AccountUtils.getAccountPhone(mActivity) + "#!/business/index.html";
            HPLog.i(HPLog.YL_TAG, "证券开户:" + url);
            startShowHtmlActivity("证券开户", url);
        } else if (tag.equalsIgnoreCase(FunctionInfo.MONG_HOO_CODE)) {//代还信用卡
            if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.SUCCESS) {
                String host = mDBModel.queryComponent(info.itemId).getItemUrl();
                if (TextUtils.isEmpty(host)) {
                    host = "https://www.monghoo.com/index_hyin.html#/user";
                }
                Intent intent = new Intent(mActivity, info.cls);
                intent.putExtra(ShowLoanHtmlActivity.ShowHtml_Html_Path_Key, host);
                mActivity.startActivity(intent);
            } else {
                mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), mActivity.getString(R.string.toast_need_tip1));
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.LOAN_CODE)) {//贷款
            String host = mDBModel.queryComponent(info.itemId).getItemUrl();
            if (TextUtils.isEmpty(host)) {
                host = "https://www.handmart.cn/web/loan/banners.html";
            }
            startShowHtmlActivity(mActivity.getString(R.string.loan_title), host);
        } else if (tag.equalsIgnoreCase(FunctionInfo.JIEAN_CODE)) {//捷安借贷
            if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.SUCCESS) {
                Intent intent = new Intent(mActivity, info.cls);
                String host = mDBModel.queryComponent(info.itemId).getItemUrl();
                if (TextUtils.isEmpty(host)) {
                    host = "https://jieandata.cn/api/go/V1";
                }
                intent.putExtra(JieAnHtmlActivity.ShowHtml_Html_Path_Key, host);
                mActivity.startActivity(intent);
            } else {
                mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), mActivity.getString(R.string.toast_need_tip1));
            }
        } else if (tag.equals(FunctionInfo.SCAN_PAYMENT_CODE) || tag.equals(FunctionInfo.QR_CODE_CODE)) {//扫码支付
            if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.SUCCESS) {
                Intent intent = new Intent(mActivity, info.cls);
                String host;

                host = mDBModel.queryComponent(info.itemId).getItemUrl();
                if (TextUtils.isEmpty(host)) {
                    host = "https://scan.handpay.cn/hpayMicroWap/scanpay/index.htm";
                }

                intent.putExtra(ScannerCodePayActivity.ShowHtml_Html_Path_Key, host);
                intent.putExtra(ScannerCodePayActivity.Action_Key, tag);
                mActivity.startActivity(intent);
            } else {
                mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), mActivity.getString(R.string.toast_need_tip1));
            }
        } else {
            Intent intent = new Intent(mActivity, info.cls);
            mActivity.startActivity(intent);
        }
    }


    /***
     * 打开智齿机器人聊天界面
     */
    private void openSoBotApplication() {
        String appKey = "49f491f846404dddaffd28898f63af9c";
        Information info = new Information();
        LogUtils.setIsDebug(true);//关闭调试日志
        info.setAppkey(appKey);
        info.setRealname(ClientEngine.CHANNEL + "@" + AccountUtils.getAccountName(mActivity));//用户姓名
        info.setUname(ClientEngine.CHANNEL + "@" + AccountUtils.getAccountName(mActivity));//用户昵称
        info.setUid(ClientEngine.CHANNEL + "@" + AccountUtils.getAccountName(mActivity));
        info.setShowSatisfaction(true);
        SobotApi.startSobotChat(mActivity, info);
    }

    private void startTransferActivity(FunctionInfo info, boolean b) {
        byte type = ZZTongActivity.Action_CreditCardRepay;
        if (info.itemId.equalsIgnoreCase(FunctionInfo.FAST_TRANSFER_CODE)) {
            type = ZZTongActivity.Action_SuperTransfer;
        }
        if (mActivity.requestCurrentLocation(true) == true) {
            if (AccountUtils.AccountStatus.SUCCESS == AccountUtils.getAccountStatus(mActivity)) {
                if (b) {
                    Intent intent = new Intent(mActivity, info.cls);
                    intent.putExtra(ZZTongActivity.ACTION, type);
                    mActivity.startActivity(intent);
                } else {
                    gotoSuperTransfer(type, info.cls);
                }

            } else {
                // 提示用户
                showNeedUpload();
            }
        }
    }

    private void startShowHtmlActivity(String title, String key) {
        Intent intent1 = new Intent(mActivity, ShowHtmlActivity.class);
        intent1.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, title);
        intent1.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, key);
        mActivity.startActivity(intent1);
    }

    private void showNeedUpload() {
        mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), mActivity.getString(R.string.toast_need_upload));
    }

    private void gotoSuperTransfer(final byte actionType, final Class<?> cls) {
        mActivity.setMode(SwiperMode.SUPER_TRANS, false, new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(mActivity, cls);
                intent.putExtra(ZZTongActivity.ACTION, actionType);
                mActivity.startActivity(intent);
            }
        });
    }

    private void startShowPaymentHtmlActivity(String title, String key) {
        Intent intent1 = new Intent(mActivity, ShowMarketHtmlActivity.class);
        intent1.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, title);
        intent1.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, key);
        mActivity.startActivity(intent1);
    }

    public void swiperConnect(Intent intent) {
        if (mActivity.getClass() == MainActivity.class) {
            ((MainActivity) mActivity).getCurrentFragment().swiperSelect(intent);
        }

    }

    protected void doWithDrawCash() {
        if (AccountUtils.getAccountStatus(mActivity).equals(AccountUtils.AccountStatus.SUCCESS) && AccountUtils.isWDVisible(mActivity)) {
            Intent intent = new Intent(mActivity, WithdrawActivity.class);
//            intent1.putExtra("money", fmoney);
            mActivity.startActivity(intent);
        } else {
            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), mActivity.getString(R.string.withdraw_message), true);
        }
    }


    protected void switchPage() {
        if (mActivity.getClass() == MainActivity.class) {
            ((MainActivity) mActivity).switchPage(ZZTConstant.BTN_FLAG_RECEIVABLES);
        } else if (mActivity.getClass() == AllFunctionActivity.class) {
            mActivity.finish();
            ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.SWITCH_RECEIVABLES_ACTION, null);
        }
    }
}
